package com.bhh.socket;

import lombok.extern.slf4j.Slf4j;

import java.io.*;
import java.net.Socket;

/**
 * @author bhh
 * @description 测试Socket, 配合SocketServerTest类使用
 * 该类是客户端
 * @date Created in 2021-04-06 20:01
 * @modified By
 */
@Slf4j
public class SocketClientTest {

    public static void main(String[] args) {

        final String SERVER_IP = "127.0.0.1";
        final int SERVER_PORT = 8888;
        BufferedWriter writer = null;
        final String QUIT = "quit";
        Socket socket = null;

        // 使用try-with-resource方式创建Socket, 确保使用完后, Socket会被关闭
        // 创建Socket
        try {
            socket = new Socket(SERVER_IP, SERVER_PORT);
            // 创建IO流
            writer = new BufferedWriter(
                    new OutputStreamWriter(socket.getOutputStream())
            );
            BufferedReader reader = new BufferedReader(
                    new InputStreamReader(socket.getInputStream())
            );

            String input = null;
            while (!QUIT.equals(input)) {
                // 写数据, 发送消息给服务器
                BufferedReader systemReader = new BufferedReader(
                        new InputStreamReader(System.in));
                input = systemReader.readLine();
                writer.write(input + "\n");
                writer.flush();

                // 读数据, 读取服务器的消息
                String msg = reader.readLine();
                if (msg != null) {
                    log.info(msg);
                }
            }
        } catch (Exception e) {

        } finally {
            if (writer != null) {
                try {
                    writer.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                System.out.println("socket.isClosed() = " + socket);
            }
        }
    }
}
